package com.last1mile.web.control;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;

import com.last1mile.model.Customer;
import com.last1mile.service.UserService;
import com.last1mile.validator.CustomerValidator;

@Controller
@RequestMapping("/registry.html")
public class RegistryController {

    @Autowired
    @Qualifier("customerValidator")
    CustomerValidator customerValidator;

    @Autowired
    @Qualifier("userServiceImpl")
    UserService       userService;

    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(@ModelAttribute("customer") Customer customer, BindingResult result,
                                SessionStatus status) {
        customerValidator.validate(customer, result);

        if (result.hasErrors()) {
            return "user/RegistryForm";
        } else {
            this.userService.createUser(customer);
            return "user/RegistrySuccess"; // FIXME 跳转要实现外部重定向以避免刷新页面的重复提交
        }
    }

    @RequestMapping(method = RequestMethod.GET)
    public String initForm(@ModelAttribute("customer") Customer customer, ModelMap model) {
        return "user/RegistryForm";
    }
}
